import db from '../database.js';

// 获取模型的所有状态
export const getModelStates = (req, res) => {
  try {
    const { modelId } = req.params;
    const states = db.prepare(`
      SELECT * FROM model_states 
      WHERE model_id = ? 
      ORDER BY order_num ASC
    `).all(modelId);
    
    res.json(states.map(state => ({
      ...state,
      canvas_data: JSON.parse(state.canvas_data)
    })));
  } catch (error) {
    console.error('获取模型状态失败:', error);
    res.status(500).json({ error: '获取模型状态失败' });
  }
};

// 创建新状态（基于母版）
export const createState = (req, res) => {
  try {
    const { modelId } = req.params;
    const { button_label, canvas_data, order_num } = req.body;
    
    if (!button_label || !canvas_data) {
      return res.status(400).json({ error: '缺少必填字段' });
    }
    
    // 验证模型是否存在
    const model = db.prepare('SELECT id, canvas_data FROM geometry_models WHERE id = ?').get(modelId);
    if (!model) {
      return res.status(404).json({ error: '模型不存在' });
    }
    
    // 如果没有提供 order_num，自动设置为最大值+1
    let finalOrderNum = order_num;
    if (finalOrderNum === undefined) {
      const maxOrder = db.prepare('SELECT MAX(order_num) as max FROM model_states WHERE model_id = ?').get(modelId);
      finalOrderNum = (maxOrder?.max || 0) + 1;
    }
    
    const result = db.prepare(`
      INSERT INTO model_states (model_id, button_label, canvas_data, order_num)
      VALUES (?, ?, ?, ?)
    `).run(modelId, button_label, JSON.stringify(canvas_data), finalOrderNum);
    
    const newState = db.prepare('SELECT * FROM model_states WHERE id = ?').get(result.lastInsertRowid);
    
    res.status(201).json({
      ...newState,
      canvas_data: JSON.parse(newState.canvas_data)
    });
  } catch (error) {
    console.error('创建状态失败:', error);
    res.status(500).json({ error: '创建状态失败' });
  }
};

// 更新状态
export const updateState = (req, res) => {
  try {
    const { id } = req.params;
    const { button_label, canvas_data, order_num } = req.body;
    
    const state = db.prepare('SELECT * FROM model_states WHERE id = ?').get(id);
    if (!state) {
      return res.status(404).json({ error: '状态不存在' });
    }
    
    const updates = [];
    const params = [];
    
    if (button_label !== undefined) {
      updates.push('button_label = ?');
      params.push(button_label);
    }
    if (canvas_data !== undefined) {
      updates.push('canvas_data = ?');
      params.push(JSON.stringify(canvas_data));
    }
    if (order_num !== undefined) {
      updates.push('order_num = ?');
      params.push(order_num);
    }
    
    updates.push('updated_at = CURRENT_TIMESTAMP');
    params.push(id);
    
    db.prepare(`
      UPDATE model_states 
      SET ${updates.join(', ')}
      WHERE id = ?
    `).run(...params);
    
    const updatedState = db.prepare('SELECT * FROM model_states WHERE id = ?').get(id);
    
    res.json({
      ...updatedState,
      canvas_data: JSON.parse(updatedState.canvas_data)
    });
  } catch (error) {
    console.error('更新状态失败:', error);
    res.status(500).json({ error: '更新状态失败' });
  }
};

// 删除状态
export const deleteState = (req, res) => {
  try {
    const { id } = req.params;
    
    const state = db.prepare('SELECT * FROM model_states WHERE id = ?').get(id);
    if (!state) {
      return res.status(404).json({ error: '状态不存在' });
    }
    
    db.prepare('DELETE FROM model_states WHERE id = ?').run(id);
    
    res.json({ message: '状态删除成功' });
  } catch (error) {
    console.error('删除状态失败:', error);
    res.status(500).json({ error: '删除状态失败' });
  }
};

// 批量更新状态顺序
export const reorderStates = (req, res) => {
  try {
    const { modelId } = req.params;
    const { states } = req.body; // [{ id, order_num }, ...]
    
    if (!Array.isArray(states)) {
      return res.status(400).json({ error: '无效的状态列表' });
    }
    
    const updateStmt = db.prepare('UPDATE model_states SET order_num = ? WHERE id = ? AND model_id = ?');
    
    const transaction = db.transaction((statesList) => {
      for (const state of statesList) {
        updateStmt.run(state.order_num, state.id, modelId);
      }
    });
    
    transaction(states);
    
    res.json({ message: '顺序更新成功' });
  } catch (error) {
    console.error('更新顺序失败:', error);
    res.status(500).json({ error: '更新顺序失败' });
  }
};

